package com.yan.club.auth.model;

import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 彦
 * @since 2024/1/19 15:10
 */
@Data
public class LoginUser implements UserDetails {

    private AuthUser user;

    /**
     * 权限信息
     */
    private List<String> permissions;

    /**
     * 不序列化这个属性 不存入redis
     */
    private transient List<SimpleGrantedAuthority> authorities;

    public LoginUser(AuthUser user, List<String> permissions) {
        this.user = user;
        this.permissions = permissions;
    }

    /**
     * List<String> -->  List<SimpleGrantedAuthority>
     *
     * @return
     */
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        // 优化 使其不用每次都转换 转换一次就可以
        if (authorities != null) {
            return authorities;
        }
        // 把permissions中String类型的权限信息封装成SimpleGrantedAuthority对象
        authorities = permissions.stream()
                .map(SimpleGrantedAuthority::new)
                .collect(Collectors.toList());

        return authorities;
//        return  null;
    }

    @Override
    public String getPassword() {
        return user.getPassword();
    }

    @Override
    public String getUsername() {
        return user.getUserName();
    }

    /**
     * 账号是否未过期
     *
     * @return
     */
    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    /**
     * 账号是否未锁定
     *
     * @return
     */
    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    /**
     * 用户凭证（密码）是否未过期
     *
     * @return
     */
    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    /**
     * 用户是否启用
     *
     * @return
     */
    @Override
    public boolean isEnabled() {
        return "0".equals(user.getStatus()) && "0".equals(user.getDelFlag());
    }
}
